import { reactive, readonly, watch, toRaw } from '@vue-mini/wechat';
import { _store } from './state.js';

const STORAGE_KEY = 'vuex';

// 可以使用 readonly 避免外部直接修改 store
export const store = readonly(_store);

// 本地存储
export function initStore() {
  let stateString = wx.getStorageSync(STORAGE_KEY) || '{}';
  if (stateString == '') stateString = '{}';

  let stateRaw = {};
  try {
    stateRaw = JSON.parse(stateString) || {};
  } catch (error) {
    console.error(error);
  }

  Object.entries(stateRaw).forEach(([k, value]) => {
    _store[k] = value;
  });
}

function setItem(state) {
  const stateString = JSON.stringify(state);
  wx.setStorageSync(STORAGE_KEY, stateString);
}

watch(_store, () => {
  const stateRow = toRaw(_store);
  setItem(stateRow);
});
